import { ref } from 'vue'
import axios from 'axios'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 示例token，实际应该从localStorage获取
const DEMO_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsicGhvbmUiOiIxMzEzNTY3ODU2NyIsIm5hbWUiOiJ4aWp1cmUiLCJpZCI6MX0sImV4cCI6MTc1OTY0NTYyMn0.e2FE28CKQYTlFvZanCneg0k_suOoAUjgtvvN-CuwQEc'

// 请求拦截器
http.interceptors.request.use(
  config => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = token
    } else {
      // 如果没有token则使用示例token
      config.headers.Authorization = DEMO_TOKEN
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

// 获取收藏列表
export async function getFavorites() {
  try {
    const response = await http.get('/auth/user/favorites')
    // 根据接口文档，返回格式为 { code: 200, data: [...] }
    const favorites = Array.isArray(response) ? response : (response?.data ?? [])
    return favorites
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    throw error
  }
}

// 添加收藏
export async function addFavorite(houseId) {
  try {
    const response = await http.post('/auth/user/favorites',  
      houseId
    )
    console.log('收藏成功:', response)
    return response
  } catch (error) {
    console.error('收藏房源失败:', error)
    throw error
  }
}

// 取消收藏
export async function removeFavorite(houseId) {
  try {
    const response = await http.delete(`/auth/user/favorites/${houseId}`)
    console.log('取消收藏成功:', response)
    return response
  } catch (error) {
    console.error('取消收藏失败:', error)
    throw error
  }
}

// 检查是否已收藏（通过获取收藏列表判断）
export async function isFavorited(houseId) {
  try {
    const favorites = await getFavorites()
    return favorites.some(item => item.id === houseId || item.id === String(houseId))
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return false
  }
}

// 响应式数据
export const favorites = ref([])
export const loading = ref(false)
export const error = ref('')

// 刷新收藏列表
export async function refreshFavorites() {
  loading.value = true
  error.value = ''
  try {
    const list = await getFavorites()
    favorites.value = list || []
    return list
  } catch (e) {
    error.value = '获取收藏列表失败'
    console.error(e)
    throw e
  } finally {
    loading.value = false
  }
}

export default http
